package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {
    @Reference
    private OrderSettingService orderSettingService;

    //Excel文件上传,并解析文件数据保存到数据库  List<String[]>=> List<OrderSetting>
    @RequestMapping("/uploadAndSaveData")
    public Result uploadAndSaveData(@RequestParam("excelFile") MultipartFile excelFile) {
        try {
            //获取上传表格文件数据封装到集合中
            List<String[]> list = POIUtils.readExcel(excelFile);

            if (list != null && list.size() > 0) {
                List<OrderSetting> orderSettingList = new ArrayList<>();

                //遍历集合,把String泛型集合转成List<OrderSetting>类型
                for (String[] strings : list) {
                    //日期字符串数据
                    String dateString = strings[0];
                    //可预约数量
                    String countString = strings[1];
                    OrderSetting orderSetting = new OrderSetting(new Date(dateString), Integer.parseInt(countString));

                    orderSettingList.add(orderSetting);
                }
                //调用业务层批量导入预约设置数量的方法
                orderSettingService.addOrderSettings(orderSettingList);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
        return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }

    //通过当前页的年-月(2020-8) , 查询当月的所有预约设置信息数据
    @RequestMapping("/getOrderSettingByYearAndMonth")
    public Result getOrderSettingByYearAndMonth(String date) {//2020-8
        try {
            //调用业务层查询预约设置方法,得到返回前端的数据
            //返回数据格式为  { date: 1, number: 120, reservations: 1 } 的集合
            List<Map> orderSettingMapList = orderSettingService.getOrderSettingByYearAndMonth(date);
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, orderSettingMapList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    //根据指定日期修改可预约人数
    @RequestMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting) {

        try {
            orderSettingService.editNumberByDate(orderSetting);
            return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);
        }
    }
}
